package xyj.sparrow.client.proxy;

import xyj.sparrow.common.netty.bean.Request;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import xyj.sparrow.client.NettyClient;
import xyj.sparrow.client.annotation.Service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RpcProxy implements InvocationHandler {
    private final NettyClient nettyClient;

    public RpcProxy(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Request request = new Request();
        Class<?> declaringClass = method.getDeclaringClass();
        request.setClassName(declaringClass.getName());
        Service annotation = declaringClass.getAnnotation(Service.class);
        String aliasName = declaringClass.getName().substring(declaringClass.getName().lastIndexOf(".") + 1);
        if (annotation != null) {
            aliasName = StrUtil.isBlank(annotation.aliasName()) ? aliasName : annotation.aliasName();
        }
        if (Character.isUpperCase(aliasName.charAt(0))) {
            aliasName = Character.toLowerCase(aliasName.charAt(0)) + aliasName.substring(1);
        }
        request.setAliasName(aliasName);
        request.setMethodName(method.getName());
        request.setParams(args);
        request.setParamTypes(method.getParameterTypes());
        assert annotation != null;
        request.setRequestType(StrUtil.isBlank(annotation.requestType()) ? Request.RequestType.TRANSFER :
                annotation.requestType());
        request.setRequestId(IdUtil.simpleUUID());
//        SynchronousQueue<Object> queue = nettyClient.getNettyClientHandler().send(nettyClient.getChannel(), request);
        nettyClient.getNettyClientHandler().send(nettyClient.getChannel(), request);
        //超时异常 30s
//        return queue.poll(30, TimeUnit.SECONDS);
        return null;
    }
}
